package com.sjy.project.ent.api;

import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.sjy.framework.aspectj.lang.annotation.Log;
import com.sjy.framework.aspectj.lang.enums.BusinessType;
import com.sjy.project.ent.data.service.IEntDataService;
import com.sjy.project.ent.user.domain.EntUser;
import com.sjy.project.ent.user.service.IEntUserService;

import cn.hutool.crypto.digest.MD5;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

import com.sjy.framework.web.controller.BaseController;
import com.sjy.framework.web.domain.AjaxResult;
import com.google.common.base.Preconditions;
import com.sjy.common.constant.UserContext;
import com.sjy.common.entity.SecuryUserDetail;
import com.sjy.common.result.BaseResponse;
import com.sjy.common.utils.AesEncrypt;
import com.sjy.common.utils.Md5Utils;
import com.sjy.common.utils.PwdCheckUtil;
import com.sjy.common.utils.StringUtils;
import com.sjy.common.utils.poi.ExcelUtil;
import com.sjy.framework.web.page.TableDataInfo;

/**
 * 企业用户信息Controller
 * 
 * @author ljb
 * @date 2022-06-04
 */
@RestController
@Api(value = "亩均档案管理接口相关", tags = {"亩均接口"})
@RequestMapping("/api/ent/user")
public class ApiEntUserController extends BaseController
{
    @Autowired
    private IEntUserService entUserService;
    
	/**
     * 新增保存企业档案信息
     */
    @ApiOperation(value = "201、新增企业用户信息", position = 201, notes = "")
    @ApiImplicitParams({
    	@ApiImplicitParam(name = "userName", value = "用户名/账号", required = false, example = ""),
		@ApiImplicitParam(name = "password", value = "密码", required = false, example = "海城街道"),
		@ApiImplicitParam(name = "frname", value = "法定代表人", required = false, example = "xx"),
		@ApiImplicitParam(name = "realName", value = "姓名", required = false, example = "xx"),
		@ApiImplicitParam(name = "creditCode", value = "统代", required = false, example = "xx"),
		@ApiImplicitParam(name = "mobile", value = "手机号", required = false, example = "林"),
		@ApiImplicitParam(name = "name", value = "县级账号：政务单位名称", required = false, example = ""),
		@ApiImplicitParam(name = "position", value = "职位", required = false, example = "158"),
		@ApiImplicitParam(name = "status", value = "状态:1可用,0禁用", required = false, example = "林"),
		@ApiImplicitParam(name = "unitLevel", value = "单位级别（用户） 1-县级政务用户 2-乡镇街道政务用户 3-企业用户", required = false, example = "林"),
		@ApiImplicitParam(name = "entName", value = "企业名称", required = false, example = "林"),
		@ApiImplicitParam(name = "contactName", value = "联系人", required = false, example = "林")
	})
    @PostMapping("/add")
    public ResponseEntity<BaseResponse> addSave(@ApiIgnore EntUser entUser)
    {
    	//检测是否有重名CreditCode
    	EntUser exist = entUserService.selectEntUserByCreditCode(entUser.getCreditCode());
    	if(exist!=null) {
    		return BaseResponse.generateBadResponseEntity("新增失败-当前统代已存在", entUser);
    	}

    	SecuryUserDetail user = UserContext.getUserSession();
    	entUser.setCreateBy(user.getLoginName());
    	
    	int flag = entUserService.insertEntUser(entUser);
    	if(flag>0) {
        	return BaseResponse.generateOKResponseEntity("新增成功"); 
    	}
    	return BaseResponse.generateBadResponseEntity("新增失败", entUser);
    }
    
    /**
     * 删除企业档案信息
     */
    @Log(title = "企业档案信息", businessType = BusinessType.DELETE)
    @ApiOperation(value = "202、删除企业用户信息", position = 202, notes = "英文半角逗号分割")
    @ApiImplicitParams({
	  @ApiImplicitParam(name = "ids", value = "id ,拼接字符串", required = false, example = "海城"),
		 
	 })
    @PostMapping( "/remove")
    public ResponseEntity<BaseResponse<String>> remove(String ids)
    {
    	int flag = entUserService.deleteEntUserByIds(ids);
    	if(flag>0) {
        	return BaseResponse.generateOKResponseEntity("删除成功"); 
    	}
        return BaseResponse.generateBadResponseEntity("删除失败", ids);
    }
    
    /**
     * 修改保存企业档案信息
     */
    @Log(title = "企业档案信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ApiOperation(value = "203、修改企业用户登录信息", position = 203, notes = "")
    @ApiImplicitParams({
		@ApiImplicitParam(name = "userName", value = "用户名/账号", required = false, example = ""),
		@ApiImplicitParam(name = "oldPassword", value = "原密码", required = false, example = "海城街道"),
		@ApiImplicitParam(name = "password", value = "密码", required = false, example = "海城街道"),
		@ApiImplicitParam(name = "frname", value = "法定代表人", required = false, example = "xx"),
		@ApiImplicitParam(name = "realName", value = "姓名", required = false, example = "xx"),
		@ApiImplicitParam(name = "creditCode", value = "统代", required = false, example = "xx"),
		@ApiImplicitParam(name = "mobile", value = "手机号", required = false, example = "林"),
		@ApiImplicitParam(name = "name", value = "县级账号：政务单位名称", required = false, example = ""),
		@ApiImplicitParam(name = "position", value = "职位", required = false, example = "158"),
		@ApiImplicitParam(name = "status", value = "状态:1可用,0禁用", required = false, example = "林"),
		@ApiImplicitParam(name = "unitLevel", value = "单位级别（用户） 1-县级政务用户 2-乡镇街道政务用户 3-企业用户", required = false, example = "林"),
		@ApiImplicitParam(name = "entName", value = "企业名称", required = false, example = "林"),
		@ApiImplicitParam(name = "contactName", value = "联系人", required = false, example = "林")
		 
	 })
    public ResponseEntity<BaseResponse> editSave(@ApiIgnore EntUser entUser,String oldPassword)
    {
    	SecuryUserDetail user = UserContext.getUserSession();
    	if(!"企业".equals(user.getUserType())) {
    		return BaseResponse.generateBadResponseEntity("只有企业用户才能修改密码", null);
    	}
    	
    	entUser.setCreditCode(AesEncrypt.decryptWithBase64(entUser.getCreditCode()));
//    	entUser.setUserName(AesEncrypt.decryptWithBase64(entUser.getUserName()));
    	entUser.setPassword(Md5Utils.hash(AesEncrypt.decryptWithBase64(entUser.getPassword())));
    	oldPassword = Md5Utils.hash(AesEncrypt.decryptWithBase64(oldPassword));
    	//entUser.setPassword(Md5Utils.hash(entUser.getPassword()));
    	
    	EntUser oldUser = entUserService.selectEntUserById(user.getUserId());
    	if(!oldPassword.equals(oldUser.getPassword())) {
    		return BaseResponse.generateBadResponseEntity("密码错误", null);
    	}
    	
    	if(oldUser.getFirstLogin()==0&&oldUser.getPassword().equals(entUser.getPassword())) {
    		return BaseResponse.generateBadResponseEntity("修改后的密码与之前一致", null);
    	}
    	entUser.setId(oldUser.getId());
    	entUser.setUpdateBy(user.getLoginName());
    	entUser.setFirstLogin(1);//0为首次 1为不是首次登录
    	int flag = entUserService.updateEntUser(entUser);
    	if(flag>0) {
        	return BaseResponse.generateOKResponseEntity("修改成功"); 
    	}
        return BaseResponse.generateBadResponseEntity("修改失败", null);
    }
    
    
    /**
     * 修改保存企业档案信息
     */
    @Log(title = "企业档案信息", businessType = BusinessType.UPDATE)
    @PostMapping("/noToken/editPassword")
    @ApiOperation(value = "204、修改企业用户密码等", position = 204, notes = "")
    @ApiImplicitParams({
		@ApiImplicitParam(name = "userName", value = "用户名/账号", required = false, example = ""),
		@ApiImplicitParam(name = "oldPassword", value = "原密码", required = false, example = "海城街道"),
		@ApiImplicitParam(name = "password", value = "密码", required = false, example = "海城街道"),
		@ApiImplicitParam(name = "frname", value = "法定代表人", required = false, example = "xx"),
		@ApiImplicitParam(name = "realName", value = "姓名", required = false, example = "xx"),
		@ApiImplicitParam(name = "creditCode", value = "统代", required = false, example = "xx"),
		@ApiImplicitParam(name = "mobile", value = "手机号", required = false, example = "林"),
		@ApiImplicitParam(name = "name", value = "县级账号：政务单位名称", required = false, example = ""),
		@ApiImplicitParam(name = "position", value = "职位", required = false, example = "158"),
		@ApiImplicitParam(name = "status", value = "状态:1可用,0禁用", required = false, example = "林"),
		@ApiImplicitParam(name = "unitLevel", value = "单位级别（用户） 1-县级政务用户 2-乡镇街道政务用户 3-企业用户", required = false, example = "林"),
		@ApiImplicitParam(name = "entName", value = "企业名称", required = false, example = "林"),
		@ApiImplicitParam(name = "contactName", value = "联系人", required = false, example = "林")
		 
	 })
    public ResponseEntity<BaseResponse> editPassword(@ApiIgnore EntUser entUser,String oldPassword,String newPassword)
    {
    	if(!StringUtils.isBlank(entUser.getPassword())) {
    		newPassword = entUser.getPassword();
    	}
    	String password = AesEncrypt.decryptWithBase64(newPassword);
    	//密码复杂性校验
    	String checkResult = checkStrongPwd(password);
    	if(StringUtils.isNotBlank(checkResult)) {
    		return BaseResponse.generateBadResponseEntity(checkResult,null);
    	}
    	
    	entUser.setCreditCode(AesEncrypt.decryptWithBase64(entUser.getCreditCode()));
//    	entUser.setUserName(AesEncrypt.decryptWithBase64(entUser.getUserName()));
    	entUser.setPassword(Md5Utils.hash(password));
    	oldPassword = Md5Utils.hash(AesEncrypt.decryptWithBase64(oldPassword));
    	//entUser.setPassword(Md5Utils.hash(entUser.getPassword()));
    	
    	EntUser su = new EntUser();
		su.setCreditCode(entUser.getCreditCode());
		su.setPassword(oldPassword);
		List<EntUser> entUsers = entUserService.selectEntUserList(su);
		if(entUsers==null||entUsers.size()==0) {
        	return BaseResponse.generateBadResponseEntity("用户名或密码错误",null);
        }
		EntUser oldUser = entUsers.get(0);
    	
    	
    	if(oldUser.getFirstLogin()==0&&oldUser.getPassword().equals(entUser.getPassword())) {
    		return BaseResponse.generateBadResponseEntity("修改后的密码与之前一致", null);
    	}
    	entUser.setId(oldUser.getId());
    	entUser.setUpdateBy(oldUser.getCreditCode());
    	entUser.setFirstLogin(1);//0为首次 1为不是首次登录
    	int flag = entUserService.updateEntUser(entUser);
    	if(flag>0) {
        	return BaseResponse.generateOKResponseEntity("修改成功"); 
    	}
        return BaseResponse.generateBadResponseEntity("修改失败", null);
    }

    
//    @ApiOperation(value = "204、获取企业档案清单", position = 204, notes = "当前页:pageNum,分页大小：pageSize,排序字段：orderByColumn，排序方式：asc")
//    @ApiImplicitParams({
//      @ApiImplicitParam(name = "id", value = "编号", required = false, example = ""),
//      @ApiImplicitParam(name = "userName", value = "用户名/账号", required = false, example = ""),
//	  @ApiImplicitParam(name = "password", value = "密码", required = false, example = "海城街道"),
//	  @ApiImplicitParam(name = "frname", value = "法定代表人", required = false, example = "xx"),
//	  @ApiImplicitParam(name = "town", value = "所属乡镇", required = false, example = "xx"),
//	  @ApiImplicitParam(name = "realName", value = "姓名", required = false, example = "xx"),
//	  @ApiImplicitParam(name = "creditCode", value = "统代", required = false, example = "xx"),
//	  @ApiImplicitParam(name = "mobile", value = "手机号", required = false, example = "林"),
//	  @ApiImplicitParam(name = "name", value = "县级账号：政务单位名称", required = false, example = ""),
//	  @ApiImplicitParam(name = "position", value = "职位", required = false, example = "158"),
//	  @ApiImplicitParam(name = "status", value = "状态:1可用,0禁用", required = false, example = "林"),
//	  @ApiImplicitParam(name = "unitLevel", value = "单位级别（用户） 1-县级政务用户 2-乡镇街道政务用户 3-企业用户", required = false, example = "林"),
//	  @ApiImplicitParam(name = "entName", value = "企业名称", required = false, example = "林"),
//	  @ApiImplicitParam(name = "contactName", value = "联系人", required = false, example = "林"),
//  	  @ApiImplicitParam(name = "pageNum", value = "当前页", required = false, example = "1"),
//  	  @ApiImplicitParam(name = "pageSize", value = "分页大小", required = false, example = "15"),
//  	  @ApiImplicitParam(name = "orderByColumn", value = "排序字段", required = false, example = "create_time"),
//  	  @ApiImplicitParam(name = "isAsc", value = "排序的方向desc或者asc", required = false, example = "asc"),
//    })
//    @PostMapping({"/list"})
//    public ResponseEntity<BaseResponse<TableDataInfo<EntUser>>> list(@ApiIgnore EntUser entUser)
//    {
//        startPage();
//        List<EntUser> list = entUserService.selectEntUserList(entUser);
//        return BaseResponse.generateOKResponseEntity(getDataTable(list));
//    }
    
//    @ApiOperation(value = "205、根据id获取场所信息详情", position = 205, notes = "")
//    @ApiImplicitParams({
//  	  @ApiImplicitParam(name = "id", value = "编号", required = false, example = "1")
//    })
//    @PostMapping({"/getById"})
//    public ResponseEntity<BaseResponse<EntUser>> getById(Long id) throws Exception
//    { 
//    	EntUser entUser = entUserService.selectEntUserById(id);
//    	if(entUser != null) {
//    		return BaseResponse.generateOKResponseEntity(entUser);
//    	}
//    	return BaseResponse.generateBadResponseEntity(500,"获取企业信息失败", entUser);
//    	
//    }
    /**
     * 导入数据
     */
//    @ApiOperation(value = "206、导入企业信息", position = 206, notes = "")
//    @Log(title = "企业档案信息", businessType = BusinessType.IMPORT)
//    @PostMapping("/importData")
//    @ApiImplicitParams({
//      @ApiImplicitParam(name = "file", value = "文件", required = false, example = "",dataType = "file"),
//	  @ApiImplicitParam(name = "updateSupport", value = "是否更新", required = false, example = ""),
//    })
//    public ResponseEntity<BaseResponse<Object>> importData(MultipartFile file, boolean updateSupport) throws Exception
//    {
//        ExcelUtil<EntUser> util = new ExcelUtil<EntUser>(EntUser.class);
//        List<EntUser> list = util.importExcel(file.getInputStream());
//        String message = entUserService.importUser(list, updateSupport);
//        return BaseResponse.generateOKResponseEntity(message);
//    }
    
    
    /**
     * 导出企业档案信息列表
     */
//    @ApiOperation(value = "207、导出企业档案信息模板", position = 207, notes = "")
//    @Log(title = "企业档案信息", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    @ApiImplicitParams({
//      @ApiImplicitParam(name = "id", value = "编号", required = false, example = ""),
//	  @ApiImplicitParam(name = "entName", value = "公司名称", required = false, example = ""),
//	  @ApiImplicitParam(name = "town", value = "所属乡镇", required = false, example = "海城街道"),
//	  @ApiImplicitParam(name = "frname", value = "法定代表人", required = false, example = "xx"),
//	  @ApiImplicitParam(name = "regcap", value = "注册资本", required = false, example = "xx"),
//	  @ApiImplicitParam(name = "regNo", value = "注册号", required = false, example = "xx"),
//	  @ApiImplicitParam(name = "creditCode", value = "统代", required = false, example = "xx"),
//	  @ApiImplicitParam(name = "address", value = "实际办公地址", required = false, example = "林"),
//	  @ApiImplicitParam(name = "esdate", value = "成立日期", required = false, example = ""),
//	  @ApiImplicitParam(name = "operateScope", value = "经营范围", required = false, example = "158"),
//	  @ApiImplicitParam(name = "province", value = "省份", required = false, example = "林"),
//	  @ApiImplicitParam(name = "city", value = "城市", required = false, example = "林"),
//	  @ApiImplicitParam(name = "county", value = "县", required = false, example = "林"),
//	  @ApiImplicitParam(name = "street", value = "镇街", required = false, example = "林"),
//	  @ApiImplicitParam(name = "dataFrom", value = "数据来源", required = false, example = "林"),
//	  @ApiImplicitParam(name = "registerTime", value = "企业注册时间", required = false, example = "林"),
//	  @ApiImplicitParam(name = "industryphy", value = "行业门类", required = false, example = "1"),
//	  @ApiImplicitParam(name = "contactTel", value = "联系电话", required = false, example = "1"),
//	  @ApiImplicitParam(name = "joinAssess", value = "是否参评 0参评，1不参评", required = false, example = "1"),
//	  @ApiImplicitParam(name = "entRule", value = "企业规模:0-规上,1-规下", required = false, example = "1"),
//	  @ApiImplicitParam(name = "dataYear", value = "数据年份", required = false, example = "1"),
//	  @ApiImplicitParam(name = "industryName", value = "行业名称", required = false, example = "1"),
//	  @ApiImplicitParam(name = "regAddress", value = "注册地址", required = false, example = "1"),
//	  @ApiImplicitParam(name = "entSubType", value = "企业二级类型：1：国有企业，2：民营企业,3：外商独资企业，4: 合资企业 5：港澳台企业", required = false, example = "1"),
//	  @ApiImplicitParam(name = "entType", value = "企业一级类型：1：企业 2：个体 4：社会组织", required = false, example = "1"),
//	  @ApiImplicitParam(name = "ammeterNum", value = "用电户号", required = false, example = "1"),
//	  @ApiImplicitParam(name = "pageNum", value = "当前页", required = false, example = "1"),
//	  @ApiImplicitParam(name = "pageSize", value = "分页大小", required = false, example = "15"),
//	  @ApiImplicitParam(name = "orderByColumn", value = "排序字段", required = false, example = "create_time"),
//	  @ApiImplicitParam(name = "isAsc", value = "排序的方向desc或者asc", required = false, example = "asc"),
//  })
//    public ResponseEntity<BaseResponse<Object>> export(@ApiIgnore EntUser entUser,HttpServletResponse response)
//    {
//        List<EntUser> list = entUserService.selectEntUserList(entUser);
//        
//        ExcelUtil<EntUser> util = new ExcelUtil<EntUser>(EntUser.class);
//        //util.exportExcel(list, "企业档案信息数据");
//        util.exportExcel(response,list, "企业信息数据", "企业信息数据.xlsx");
//        return null;
//    }
    public String checkStrongPwd(String pwd) {
    	String result = "";
        try {
            Preconditions.checkNotNull(pwd);
            if(!PwdCheckUtil.checkPasswordLength(pwd, "8", null)
                    || !PwdCheckUtil.checkContainCase(pwd)
                    || !PwdCheckUtil.checkContainDigit(pwd)
                    || !PwdCheckUtil.checkContainSpecialChar(pwd)
            ){
            	return "密码必须包含数字、字母、特殊符号且大于或等于8位";
            }
        }catch (Exception e){
            e.printStackTrace();
            return "密码格式异常";
        }
        return result;
    }
}
